package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * a10_复原IP地址复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/19
 */
public class a10_复原IP地址复习2 {

    public static void main(String[] args) {
        a10_复原IP地址复习2 test = new a10_复原IP地址复习2();
        System.out.println(test.restoreIpAddresses("101023"));
    }
    public List<String> restoreIpAddresses(String s) {
        char[] chars = s.toCharArray();
        List<String> result = new ArrayList<>();
        LinkedList<String> path = new LinkedList<>();
        traversal(result, path, chars, 0);
        return result;
    }

    private void traversal(List<String> result,
                           LinkedList<String> path,
                           char[] chars,
                           int startIdx){
        if(startIdx == chars.length && path.size() == 4){
            String collect = path.stream().collect(Collectors.joining("."));
            result.add(collect);
            return;
        }

        for (int i = startIdx; i < Math.min(startIdx + 3, chars.length); i++) {
            if (isValid(chars, startIdx, i)) {
                path.add(splitArray(chars, startIdx, i));
                traversal(result, path, chars, i + 1);
                path.removeLast();
            }
        }

    }

    private String splitArray(char[] chars,int leftIdx,int rightIdx){
        StringBuilder sb = new StringBuilder();
        while (leftIdx <= rightIdx){
            sb.append(chars[leftIdx]);
            leftIdx++;
        }
        return sb.toString();
    }

    private boolean isValid(char[] chars,int leftIdx,int rightIdx){
        StringBuilder sb = new StringBuilder();
        while (leftIdx <= rightIdx){
            sb.append(chars[leftIdx]);
            leftIdx++;
        }
        String str = sb.toString();
        if(str.startsWith("0") && str.length() > 1){
            return false;
        }

        Integer integer = Integer.valueOf(str);
        if (integer > 255) {
            return false;
        }

        return true;
    }


}
